// packageA/pages/package/kanban/kanban.js
import * as echarts from "../../../components/echarts/echarts";
const mybehavior = require("../../../../behaviors/requests")

var company = wx.getStorageSync('company')
var chart;
var chart1;
var chart2;
function drawChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart);
  const today = new Date();
  const lassMonthLastDay = new Date(today.getFullYear(), today.getMonth(), 1);

  const lastDay = lassMonthLastDay.toISOString().split('T')[0];
  const firstDay = lastDay.slice(0, 8) + '01'
  const time_gt = firstDay
  const time_lt = lastDay
  let url = "https://logisticsengineering.gree.com/container_manage_api/usage_manage/problem_num_in_each_category_for_mini_program"
  let data = {
    time_gt: time_gt,
    time_lt: time_lt,
    company: company

  }
  var token = wx.getStorageSync('token')
  wx.request({
    url: url,
    method: "post",
    data: data,
    header: {
      "Authorization": token
    },
    success(res) {
      let result = res.data.data
      let lists = []
      for (let i in result) {
        let obj = {
          value: result[i].count, name: result[i].problem_category
        }
        lists.push(obj)
      }
      var option = {

        toolbox: {
          show: true,

        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },


        legend: {
          top: '0',
          left: 'center',

        },
        series: [
          {

            name: 'Access From',
            type: 'pie',
            radius: ['15%', '45%'],
            center: ['50%', "60%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 30,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: lists,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  formatter: ' {c} ({d}%)'
                },
                labelLine: { show: true }
              }
            }


          }
        ]
      };

      chart.setOption(option);
    }
  });



}
function drawChart1(canvas, width, height, dpr) {
  chart1 = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart1);
  const today = new Date();
  const lassMonthLastDay = new Date(today.getFullYear(), today.getMonth(), 1);

  const lastDay = lassMonthLastDay.toISOString().split('T')[0];
  const firstDay = lastDay.slice(0, 8) + '01'
  const time_gt = firstDay
  const time_lt = lastDay
  let url = "https://logisticsengineering.gree.com/container_manage_api/usage_manage/problem_num_per_manage_for_mini_program"
  let data = {
    time_gt: time_gt,
    time_lt: time_lt,
    company: company,
    problem_category: '',

  }
  var token = wx.getStorageSync('token')
  wx.request({
    url: url,
    method: "post",
    data: data,
    header: {
      "Authorization": token
    },
    success(res) {
      let result = res.data.data
      let bottom_list = []
      let series_list = []

      for (let i in result) {
        bottom_list.push(result[i].problem_category)
        if (i % 2 == 0) {
          let obj = {
            value: result[i].count,
            itemStyle: {
              color: '#5555FF'
            }
          }
          series_list.push(obj)
        } else {
          let obj = {
            value: result[i].count,
            itemStyle: {
              color: '#AAFFF3'
            }
          }
          series_list.push(obj)
        }


      }

      var option1 = {
        xAxis: {
          type: 'category',
          axisLabel: { interval: 0, rotate: 30 },
          data: bottom_list
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: series_list,
            type: 'bar',
            label: {
              show: true, // 显示数值
              position: 'top' // 数值显示的位置
            }
          }
        ]
      };
      chart1.setOption(option1);
    }
  });







}
function drawChart2(canvas, width, height, dpr) {
  chart2 = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart2);
  const today = new Date();
  const lassMonthLastDay = new Date(today.getFullYear(), today.getMonth(), 1);

  const lastDay = lassMonthLastDay.toISOString().split('T')[0];
  const firstDay = lastDay.slice(0, 8) + '01'
  const time_gt = firstDay
  const time_lt = lastDay
  let url = "https://logisticsengineering.gree.com/container_manage_api/usage_manage/problem_num_per_manage_for_mini_program"
  let data = {
    time_gt: time_gt,
    time_lt: time_lt,
    company: company,
    problem_category: '',

  }
  var token = wx.getStorageSync('token')
  wx.request({
    url: url,
    method: "post",
    data: data,
    header: {
      "Authorization": token
    },
    success(res) {
      let result = res.data.data
      let bottom_list = []
      let series_list = []

      for (let i in result) {
        bottom_list.push(result[i].problem_category)
        if (i % 2 == 0) {
          let obj = {
            value: result[i].count,
            itemStyle: {
              color: '#5555FF'
            }
          }
          series_list.push(obj)
        } else {
          let obj = {
            value: result[i].count,
            itemStyle: {
              color: '#AAFFF3'
            }
          }
          series_list.push(obj)
        }

      }

      var option2 = {
        xAxis: {
          type: 'category',
          axisLabel: { interval: 0, rotate: 30 },
          data: bottom_list
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: series_list,
            type: 'bar',
            label: {
              show: true, // 显示数值
              position: 'top' // 数值显示的位置
            }
          }
        ]
      };
      chart2.setOption(option2);
    }
  });






}

Page({


  /**
   * 页面的初始数据
   */
  behaviors: [mybehavior],
  data: {
    baseUrl: "https://logisticsengineering.gree.com/container_manage_api/usage_manage",
    test_chart1: null,
    ec: {
      onInit: drawChart,

    },
    ec1: {
      onInit: drawChart1
    },
    ec2: {
      onInit: drawChart2
    },
    time_gt: "",
    time_lt: "",
    company: "",
    user_num: 0,
    option_data: [],
    month: 0,
    problem_category: '',
    options1: ["珠海格力电器股份有限公司","格力电器（合肥）有限公司","格力电器（石家庄）有限公司","格力电器（芜湖）有限公司","长沙格力暖通制冷设备有限公司","格力电器（洛阳）有限公司"],
    options2: ["珠海格力电器股份有限公司","格力电器（合肥）有限公司","格力电器（石家庄）有限公司","格力电器（芜湖）有限公司","长沙格力暖通制冷设备有限公司","格力电器（洛阳）有限公司"],
    isHidden: false,
    isHidden2: false,
    currentDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    minDate: new Date(),
    show: false,
    total: 0,
    done_total: 0,
    picker_disabled: true,
    not_total: 0,
  },

  dateShow() {
    this.setData({
      isHidden: true,
      show: true

    })
  },
  dateShow() {
    this.setData({
      isHidden: true,
      show: true

    })
  },
  onDateClose() {
    this.setData({
      isHidden: false,
      show: false

    })
  },
  onDateConfirm(e) {
    this.setData({
      show: false,
    })
    wx.showLoading({
      title: '加载中...',
    })
    const givenDateStr = this.formatDate1(new Date(e.detail))
    let daysStr = this.getFirstAndLastDayOfMonthAsString(givenDateStr);
    console.log('第一天:', daysStr.firstDayStr); // 输出: 第一天: 2025-01-01
    console.log('最后一天:', daysStr.lastDayStr);

    this.setData({
      month: givenDateStr.slice(0, 7),
      time_gt: daysStr.firstDayStr,
      time_lt: daysStr.lastDayStr,
    })
    this.getAllProblemDatas()
    this.getProblemNumDatas()
    this.getNumAndCategoryDatas()
    this.getNumAndCategoryDatas1()
    this.getRegisteredDatas()
    setTimeout(() => {
      this.setData({
        isHidden: false,
        show: false
      })
      wx.hideLoading()
    }, 1000)

  },
  getFirstAndLastDayOfMonthAsString(dateStr) {
    let date = new Date(dateStr);

    // 获取当前月份（0-11）和年份
    let month = date.getMonth();
    let year = date.getFullYear();

    // 第一天：当前月份的第一天，日期设为1
    let firstDay = new Date(year, month, 1);

    // 最后一天：下个月的第一天减一
    let lastDay = new Date(year, month + 1, 0);

    // 辅助函数：将Date对象格式化为yyyy-MM-dd字符串
    function formatDate(d) {
      let monthStr = (d.getMonth() + 1).toString().padStart(2, '0');
      let dayStr = d.getDate().toString().padStart(2, '0');
      return `${d.getFullYear()}-${monthStr}-${dayStr}`;
    }

    // 格式化第一天和最后一天的日期
    let firstDayStr = formatDate(firstDay);
    let lastDayStr = formatDate(lastDay);

    // 返回结果对象
    return {
      firstDayStr: firstDayStr,
      lastDayStr: lastDayStr
    };
  },

  getPickerVlaueClose() {
    wx.showLoading({
      title: '加载中...',
    })
    this.getAllProblemDatas()
    this.getProblemNumDatas()
    this.getNumAndCategoryDatas()
    this.getNumAndCategoryDatas1()
    this.getRegisteredDatas()

    setTimeout(() => {
      this.setData({
        isHidden2: false,
        isHidden: false,

      })
      wx.hideLoading()
    }, 1000)
  },
  getPickerVlaueClose1() {
    wx.showLoading({
      title: '加载中...',
    })
    this.getAllProblemDatas()
    this.getProblemNumDatas()
    this.getNumAndCategoryDatas()
    this.getNumAndCategoryDatas1()
    this.getRegisteredDatas()
    setTimeout(() => {
      this.setData({
        isHidden: false,
        isHidden2: false,

      })
      wx.hideLoading()
    }, 1000)

  },

  ecShow() {
    this.setData({
      isHidden: true,
      isHidden2: true,

    })
  },
  ecShow2() {
    this.setData({
      isHidden: true,
      isHidden2: true,

    })
  },
  // 更换公司
  getPickerVlaue(e) {
    wx.showLoading({
      title: '加载中...',
    })
    console.log(e.detail);
    this.setData({
      company: e.detail,
      problem_category: "",
    })
    this.getAllProblemDatas()
    this.getProblemNumDatas()
    this.getNumAndCategoryDatas()
    this.getNumAndCategoryDatas1()
    this.getRegisteredDatas()
    setTimeout(() => {
      this.setData({
        isHidden: false,
        isHidden2: false,

      })
      wx.hideLoading()
    }, 1000)
  },
  // 选择问题类别
  getPickerVlaue1(e) {
    wx.showLoading({
      title: '加载中...',
    })
    console.log(e.detail);
    this.setData({
      problem_category: e.detail
    })
    this.getAllProblemDatas()
    this.getProblemNumDatas()
    this.getNumAndCategoryDatas()
    this.getNumAndCategoryDatas1()
    this.getRegisteredDatas()
    setTimeout(() => {
      this.setData({
        isHidden: false,
        isHidden2: false,

      })
      wx.hideLoading()
    }, 1000)
  },
  // 获取--公司名称--数据
  getCompanyDatas() {
    let url = "https://logisticsengineering.gree.com/container_manage_api/data_auth_manage/get_u_permission"
    let data = {

    }
    this.post(url, data).then(res => {
      // console.log("公司名称", res.data)
      let data_list = Object.keys(res.data)

      if (res.code == 20000) {

        this.setData({
          options1: data_list,

        })

      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  // 获取--该时间段的所有问题类型--数据
  getAllProblemDatas() {
    let url = this.data.baseUrl + "/problem_category_in_company_for_mini_program"
    let data = {
      time_gt: this.data.time_gt,
      time_lt: this.data.time_lt,
      company: this.data.company

    }
    this.post(url, data).then(res => {
      console.log("该时间段的所有问题类型", res.data)

      if (res.code == 20000) {

        this.setData({
          options2: res.data,
        })

      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  // 获取--各单位每个问题类别数量--数据
  getProblemNumDatas() {
    let url = this.data.baseUrl + "/problem_num_in_each_category_for_mini_program"
    let data = {
      time_gt: this.data.time_gt,
      time_lt: this.data.time_lt,
      company: this.data.company

    }
    this.post(url, data).then(res => {
      console.log("公司每个问题类别数量", res.data)
      let result = res.data
      if (res.code == 20000) {
        let lists = []
        for (let i in result) {
          let obj = {
            value: result[i].count, name: result[i].problem_category
          }
          lists.push(obj)
        }
        let option = {

          toolbox: {
            show: true,

          },
          tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
          },

          legend: {
            top: '0',
            left: 'center',

          },
          series: [
            {

              name: 'Access From',
              type: 'pie',
              radius: ['15%', '45%'],
              center: ['50%', "60%"],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 40,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: lists,
              itemStyle: {
                normal: {
                  label: {
                    show: true,
                    formatter: ' {c} ({d}%)'
                  },
                  labelLine: { show: true }
                }
              }

            }
          ]
        };

        chart.setOption(option);
        // this.setData({
        //   option_data: lists,

        // })
        // this.drawChart()

      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  // 获取--全部问题类型以及公司查询各单位问题数量--数据
  getNumAndCategoryDatas() {
    let url = this.data.baseUrl + "/problem_num_per_manage_for_mini_program"
    let data = {
      time_gt: this.data.time_gt,
      time_lt: this.data.time_lt,
      problem_category: "",
      company: this.data.company
    }
    this.post(url, data).then(res => {
      console.log("根据问题类型以及公司查询各单位问题数量", res.data)

      if (res.code == 20000) {
        let result = res.data
        let bottom_list = []
        let series_list = []

        for (let i in result) {
          bottom_list.push(result[i].problem_category)
          if (i % 2 == 0) {
            let obj = {
              value: result[i].count,
              itemStyle: {
                color: '#5555FF'
              }
            }
            series_list.push(obj)
          } else {
            let obj = {
              value: result[i].count,
              itemStyle: {
                color: '#AAFFF3'
              }
            }
            series_list.push(obj)
          }

        }

        let option1 = {
          xAxis: {
            type: 'category',
            axisLabel: { interval: 0, rotate: 30 },
            data: bottom_list
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: series_list,
              type: 'bar',
              label: {
                show: true, // 显示数值
                position: 'top' // 数值显示的位置
              }
            }
          ]
        };
        chart1.setOption(option1);


      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  // 获取--单个根据问题类型以及公司查询各单位问题数量--数据
  getNumAndCategoryDatas1() {
    let url = this.data.baseUrl + "/problem_num_per_manage_for_mini_program"
    let data = {
      time_gt: this.data.time_gt,
      time_lt: this.data.time_lt,
      problem_category: this.data.problem_category,
      company: this.data.company
    }
    this.post(url, data).then(res => {
      console.log("根据问题类型以及公司查询各单位问题数量", res.data)

      if (res.code == 20000) {
        let result = res.data
        let bottom_list = []
        let series_list = []

        for (let i in result) {
          bottom_list.push(result[i].problem_category)
          if (i % 2 == 0) {
            let obj = {
              value: result[i].count,
              itemStyle: {
                color: '#5555FF'
              }
            }
            series_list.push(obj)
          } else {
            let obj = {
              value: result[i].count,
              itemStyle: {
                color: '#AAFFF3'
              }
            }
            series_list.push(obj)
          }

        }

        let option1 = {
          xAxis: {
            type: 'category',
            axisLabel: { interval: 0, rotate: 30 },
            data: bottom_list
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: series_list,
              type: 'bar',
              label: {
                show: true, // 显示数值
                position: 'top' // 数值显示的位置
              }
            }
          ]
        };
        chart2.setOption(option1);


      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  // 获取--查询公司月度检查与监督反馈用户的注册数量--数据
  getRegisteredDatas() {
    let url = this.data.baseUrl + "/get_problem_count"
    let data = {
      company: this.data.company,
      month: this.data.month,
    }
    this.post(url, data).then(res => {

      if (res.code == 20000) {

        this.setData({
          total: res.data.total,
          done_total: res.data.ok_count,
          not_total: res.data.total - res.data.ok_count,

        })

      } else {
        this.setData({
          total: 0,
          done_total: 0,
          not_total: 0,

        })

        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      this.setData({
        total: 0,
        done_total: 0,
        not_total: 0,

      })
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  getLastMonthDates() {
    const today = new Date();
    const lassMonthLastDay = new Date(today.getFullYear(), today.getMonth(), 1);

    const lastDay = lassMonthLastDay.toISOString().split('T')[0];
    const firstDay = lastDay.slice(0, 8) + '01'
    this.setData({
      time_gt: firstDay,
      time_lt: lastDay,
      month: lastDay.slice(0, 7),
    })

    console.log(firstDay);
    console.log(lastDay);

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let com = wx.getStorageSync('company')
    company = com
    this.setData({
      company: com,
      picker_disabled:false,
    })
    // this.getCompanyDatas()
    this.getLastMonthDates()
    this.getAllProblemDatas()
    // this.getProblemNumDatas()
    // this.getNumAndCategoryDatas()
    this.getRegisteredDatas()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {


  },

  /**
   * 生命周期函数--监听页面隐藏0.000000000000000000000000000000
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})